package com.example.toutiao.view

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.example.toutiao.R
import com.example.toutiao.utils.CommonUtils
import kotlinx.android.synthetic.main.dialog_edit.*
import kotlinx.android.synthetic.main.dialog_edit.view.*

class EditTextDialog(title:String) : BaseDialogFragment(), TextWatcher {
    private var mDialogFragmentListener:EditTextDialogListener?=null
    private var yesView: View? = null
    private var noView: View? = null
    private var maxView: View? = null
    private var rootView:View?=null
    private var title: String = title
    private var num: Int = 0
    override fun initData() {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    override fun initView(view: View) {
        yesView = view.tv_yes
        noView = view.tv_no
        maxView = view.tv_max
        view.tv_title.text=title
        view.tv_input_content.addTextChangedListener(this)
        val lp: WindowManager.LayoutParams = dialog?.window!!.attributes

        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog?.window!!.setGravity(Gravity.BOTTOM)
        rootView=view

//        先不做监听 模拟器上显示不一样
//        val rootView:View=dialog?.window!!.decorView
//        rootView.viewTreeObserver.addOnGlobalLayoutListener(CommonUtils.getGlobalListener(rootView,view.ll_input))

        view.tv_yes.setOnClickListener {
            mDialogFragmentListener!!.onDialog(view.tv_input_content.text.toString())
            dismiss()
        }
        view.tv_no.setOnClickListener {
            dismiss()
        }
    }

    fun setmDialogFragmentListener(mDialogFragmentListener: EditTextDialogListener) {
        this.mDialogFragmentListener=mDialogFragmentListener
    }

    override fun getLayout(): Int = R.layout.dialog_edit
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val content = s.toString()
        num = 30 - (content.length)
        rootView!!.tv_max.text="$num"
        if (!TextUtils.isEmpty(content)) {
            yesView!!.setBackgroundResource(R.drawable.bg_yes_dialog_text)
        } else {
            yesView!!.setBackgroundResource(R.drawable.bg_edit_dialog_text)
        }
    }

    override fun afterTextChanged(s: Editable?) {

    }
}